package com.tjbank.cssys.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SM4Utils {
    // private String secretKey = "";

    // private String iv = "";

    // private boolean hexString = false;

 private static  final     Logger logger = LoggerFactory.getLogger(SM4Utils.class);


    public String secretKey = "botjcssys@123456";
    public String iv = "123456@botjcssys";
    public boolean hexString = false;
    protected static String CHART_SET = "UTF-8";

    public SM4Utils() {
    }

    // public byte encryptData_ECB1(byte[] inputStream){
    // try
    // {
    // SM4_Context ctx = new SM4_Context();
    // ctx.isPadding = true;
    // ctx.mode = SM4.SM4_ENCRYPT;
    //
    // byte[] keyBytes;
    // if (hexString)
    // {
    // keyBytes = Util.hexStringToBytes(secretKey);
    // }
    // else
    // {
    // keyBytes = secretKey.getBytes();
    // }
    //
    // SM4 sm4 = new SM4();
    // sm4.sm4_setkey_enc(ctx, keyBytes);
    // String cipherText = new BASE64Encoder().encode(inputStream);
    // if (cipherText != null && cipherText.trim().length() > 0)
    // {
    // Pattern p = Pattern.compile("\\s*|\t|\r|\n");
    // Matcher m = p.matcher(cipherText);
    // cipherText = m.replaceAll("");
    // }
    // return cipherText;
    // }
    // catch (Exception e)
    // {
    // return (Byte) null;
    // }
    // }
    public String encryptData_ECB(String plainText) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;
            byte[] keyBytes;
            if (hexString) {
                keyBytes = hexStr2Byte(secretKey);
            } else {
                keyBytes = secretKey.getBytes();
            }
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes(CHART_SET));
            String cipherText = new BASE64Encoder().encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        } catch (Exception e) {
            logger.error("encryptData_ECB异常"+e.getMessage());
            return null;
        }
    }

    public String decryptData_ECB(String cipherText) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;
            byte[] keyBytes;
            if (hexString) {
                keyBytes = hexStr2Byte(secretKey);
            } else {
                keyBytes = secretKey.getBytes();
            }
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, new BASE64Decoder().decodeBuffer(cipherText));
            return new String(decrypted, "GBK");
        } catch (Exception e) {
            logger.error("encryptData_ECB异常"+e.getMessage());

            return null;
        }
    }

    public String encryptData_CBC(String plainText) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;
            byte[] keyBytes;
            byte[] ivBytes;
            if (hexString) {
                keyBytes = hexStr2Byte(secretKey);
                ivBytes = hexStr2Byte(iv);
            } else {
                keyBytes = secretKey.getBytes();
                ivBytes = iv.getBytes();
            }
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, plainText.getBytes(CHART_SET));
            String cipherText = new BASE64Encoder().encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }
            return cipherText;
        } catch (Exception e) {
            logger.error("SM$UTILS异常"+e.getMessage());
            return null;
        }
    }

    public String decryptData_CBC(String cipherText) {
        try {
            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;
            byte[] keyBytes;
            byte[] ivBytes;
            if (hexString) {
                keyBytes = hexStr2Byte(secretKey);
                ivBytes = hexStr2Byte(iv);
            } else {
                keyBytes = secretKey.getBytes();
                ivBytes = iv.getBytes();
            }
            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
            return new String(decrypted, CHART_SET);
        } catch (Exception e) {
            logger.error("decryptData_CBCSM$异常"+e.getMessage());
            return null;
        }
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] hexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
